/**
 * 路由拦截操作
 */
import store from '@/store'
import router, { mainRoutes, resetRouter } from './index'
import { pageLoading } from '@/utils/tools/common'
import { local, session } from '@/utils/jcore/storage'
import { getQueryObject } from '@/utils/jcore/page'
import { fnAddDynamicMenuRoutes } from './createRoute'
import { getterMenusTree } from './routerApi'
import {
  addMenuType,
  showRoute,
  showSidebar,
  fnCurrentRouteType,
  searchRouteLaster,
  addGlobalRoute
} from './routerUtils'
router.isAddDynamicMenuRoutes = false

//每个路由都进行拦截
router.beforeEach(async (to, from, next) => {
  // 进入登录页清除动态路由
  if (to.path == '/login') {
    router.isAddDynamicMenuRoutes = false
    resetRouter()
  }

  let params = getQueryObject()
  const token = params.token || session.get('token')
  if (token) {
    if (!session.get('token')) {
      session.set('token', token)
    }
    if (router.isAddDynamicMenuRoutes || fnCurrentRouteType(to)) {
      next()
    } else {
      let resRoute = null
      const loading = pageLoading()
      try {
        // 获取用户信息
        let userInfo = local.get('authorityList')

        // 获取动态路由
        resRoute = await getterMenusTree(userInfo)
        loading.close()
      } catch (error) {
        console.log(error)
        console.log(`%c${error} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
        loading.close()
        next({ path: '/login' })
        return
      }
      // 添加菜单类型
      let menuList = addMenuType(resRoute)
      // 动态注册路由
      let routes = fnAddDynamicMenuRoutes(menuList)
      // 添加全局静态路由
      routes = addGlobalRoute(routes)
      console.log(routes, '-->>> routes routesroutes')
      mainRoutes.name = 'main-dynamic'
      mainRoutes.children = routes
      router.addRoutes([mainRoutes, { path: '*', redirect: { name: '404' } }])
      router.isAddDynamicMenuRoutes = true
      await store.dispatch('app/setMenuList', routes)
      // 同步选中的导航显示侧边栏
      let firstRoute = showSidebar(routes) || routes[0]
      store.dispatch('app/setSidebarList', firstRoute)
      // 同步选中的路由
      let selectRouteName = showRoute(routes) || searchRouteLaster(firstRoute)
      if (selectRouteName) {
        next({ name: selectRouteName, replace: true })
      } else {
        next({ ...to, replace: true })
      }
    }
  } else {
    if (fnCurrentRouteType(to)) {
      // 在登录白名单中，直接进入
      next()
    } else {
      // 其他没有访问权限的页面将被重定向到登录页面。
      next({ path: '/login' })
    }
  }
})
